﻿using BridgeWeChat.Constant;
using BridgeWeChat.Model;
using BridgeWebSystemLib.Core;
using BridgeWebSystemLib.Core.DataAccess;
using System;
using System.Collections.Generic;
using System.Text;

namespace WeChatCommon.BizLogic
{
    public class ComMessageUtil
    {
        public static MsgInfo SaveWeChatMPMessage(WeChatTemplateMessageRequest messageRequest,string WeChatMsgId)
        {
            MsgInfo msgInfo = MsgInfo.CreateMsgInfo();
            try
            {
                using (IDataAccess dataAccess = BridgeHttpContext.DataAccess)
                {
                    var message = new COM_MESSAGE();
                    message.MSG_TYPE = (int)ComEnum.平台消息类型.微信公众号;
                    message.ORGAN_ID = messageRequest.OrganId;
                    message.USER_ID = messageRequest.UserId;
                    message.OPEN_ID = messageRequest.OpenId;
                    message.TEMPLATE_TYPE = messageRequest.TemplateType;
                    message.HPD_MSG_ID = messageRequest.MessageId;
                    message.WX_MSG_ID = WeChatMsgId;
                    message.CALLBACK_URL = messageRequest.CallbackUrl;
                    message.HPD_MSG_ID = messageRequest.MessageId;
                    message.OPER_DATE = DateTime.Now;
                    dataAccess.Insert(message);
                }
            }
            catch (Exception ex)
            {
                msgInfo.State = false;
                msgInfo.Message = ex.Message;
                msgInfo.Exception = ex;
            }
            return msgInfo;
        }

        public static MsgInfo UpdateWeChatMPMessageState(string wxMsgId,string msgState)
        {
            MsgInfo msgInfo = MsgInfo.CreateMsgInfo();
            try
            {
                using (IDataAccess dataAccess = BridgeHttpContext.DataAccess)
                {
                    var message = dataAccess.GetByParam<COM_MESSAGE>(new { MSG_TYPE = (int)ComEnum.平台消息类型.微信公众号, WX_MSG_ID = wxMsgId });
                    if (message == null)
                    {
                        throw new Exception("不存在微信消息ID:" + wxMsgId);
                    }
                    message.MSG_STATE = msgState;
                    
                    dataAccess.Update(message);
                }
            }
            catch (Exception ex)
            {
                msgInfo.State = false;
                msgInfo.Message = ex.Message;
                msgInfo.Exception = ex;
            }
            return msgInfo;
        }
    }
}
